package com.naton.common.ui;

import android.os.Build;
import android.view.LayoutInflater;

import androidx.viewbinding.ViewBinding;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class ViewBindingCreator {

    @SuppressWarnings("unchecked")
    public static <VB extends ViewBinding> VB createViewBinding(Class targetClass, LayoutInflater layoutInflater) {
        Type type = targetClass.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            try {
                Type[] types = ((ParameterizedType) type).getActualTypeArguments();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    for (Type type1 : types) {
                        if (type1.getTypeName().endsWith("Binding")) {
                            Method method = ((Class<VB>) type1).getMethod("inflate", LayoutInflater.class);
                            return (VB) method.invoke(null, layoutInflater);
                        }
                    }
                } else {
                    Type superclass = targetClass.getGenericSuperclass();
                    Class<?> aClass = (Class<?>) ((ParameterizedType) superclass).getActualTypeArguments()[0];
                    Method method = aClass.getDeclaredMethod("inflate", LayoutInflater.class);
                    return (VB) method.invoke(null, layoutInflater);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
